package com.linkdood.app.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linkdood.app.component.WebSocketServer;
import com.linkdood.app.constants.SystemNoticeConstants;
import com.linkdood.app.domain.SystemNotice;
import com.linkdood.app.mapper.SystemNoticeMapper;
import com.linkdood.app.service.SystemNoticeService;
import com.linkdood.app.utils.PaginationUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * 系统消息
 * @author cfj
 */
@Service
@Slf4j
public class SystemNoticeServiceImpl extends ServiceImpl<SystemNoticeMapper, SystemNotice> implements SystemNoticeService {

    private final WebSocketServer webSocketServer;

    public SystemNoticeServiceImpl(@Lazy WebSocketServer webSocketServer) {
        this.webSocketServer = webSocketServer;
    }

    /**
     * 保存系统消息
     * @param type
     */
    @Override
    public void save(String type) {
        SystemNotice systemNotice = new SystemNotice(type);
        this.save(systemNotice);
        sendMessage();
    }

    /**
     * 获取未读消息数量
     */
    @Override
    public int countUnReadNotices() {
        return lambdaQuery().eq(SystemNotice::getStatus, SystemNoticeConstants.SYSTEM_NOTICE_STATUS_UNREAD).count();
    }

    @Override
    public void sendMessage() {
        try {
            webSocketServer.sendToUser(Integer.toString(countUnReadNotices()), "");
        } catch (IOException e) {
            log.error("{}", e);
        }
    }

    @Override
    public Page<SystemNotice> pageSystemNoticesByStatus(String status, Pageable pageable) {
        return lambdaQuery()
                .eq(StringUtils.isNotEmpty(status), SystemNotice::getStatus, status)
                .page(PaginationUtil.getPage(pageable));
    }

    @Override
    public List<SystemNotice> listSystemNoticeByIds(List<String> ids) {
        return lambdaQuery().in(SystemNotice::getId, ids).list();
    }
}
